<template>
  <j-modal
    :title="$t('systemManagement.purchasingApplicationForm')"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.purchasingWarehouse')">
              <a-select @select="depotSelectChange" :placeholder="$t('popup.pleaseSelectPurWarehouse')" showSearch optionFilterProp="children" v-decorator="[ 'depotId', validatorRules.depotId ]">
                  <a-select-option v-for="(depot,index) in depotList" :value="depot.id" :key="index" >
                    {{ depot.depotName }}
                  </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.distributionWarehouse')">
              <a-select :placeholder="$t('popup.pleaseSelectDistriWarehouse')" showSearch optionFilterProp="children" v-decorator="[ 'anotherDepotId', validatorRules.anotherDepotId ]">
                  <a-select-option v-for="(depot,index) in anotherDepotList" :value="depot.id" :key="index">
                    {{ depot.name }}
                  </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('salesManagement.operator')" data-step="3" :data-title="$t('salesManagement.operator')"
              :data-intro="$t('popup.theDataComesMenu')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>

          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'number' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.arrivalDate')">
              <j-date v-decorator="['arrivalTime']" :show-time="true" :placeholder="$t('otherJS.pleaseSelectTheArrDate')"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.deliveryMethod')">
              <a-input :placeholder="$t('otherJS.pleaseEnterDeliveryMethod')" v-decorator.trim="[ 'deliveryMethod' ]"/>
            </a-form-item>
          </a-col>
        
        </a-row>
        
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :dragSort="true"
          @valueChange="barCodeValueChange"
          @inputPurchaseValueChange="onValueChange"
          @added="onAdded"
          @deleted="onDeleted">
          <template #buttonAfter>
            <a-row :gutter="24" style="float:left;" data-step="4" :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{$t('popup.codeScanningEntry')}}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input :placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">{{$t('popup.stowScanningCode')}}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;">
              <a-col :md="24" :sm="24">
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="handleBatchSetDepot"><a-icon type="setting"/>{{$t('popup.batchSettings')}}</a-menu-item>
                    <a-menu-item v-if="isTenant" key="2" @click="addDepot"><a-icon type="plus"/>{{$t('popup.newWarehouse')}}</a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px">{{$t('popup.warehouseOperation')}} <a-icon type="down" /></a-button>
                </a-dropdown>
              </a-col>
            </a-row>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import DepotModal from '../../system/modules/DepotModal'
  import BatchSetDepot from '../dialog/BatchSetDepot'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  // import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { BillModalMixin } from '../mixins/BillModalMixin'
  import { BillListMixin } from '../mixins/BillListMixin'
  import { getMpListShort } from "@/utils/util"
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  export default {
    name: "AllocationOutModal",
    mixins: [JEditableTableMixin, BillModalMixin, BillListMixin],
    components: {
      DepotModal,
      BatchSetDepot,
      JUpload,
      JDate
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        operTimeStr: '',
        prefixNo: 'YHSQD',
        fileList:[],
        model: {},
        // 查询条件
        queryParam: {
          name: '',
          type: '',
          deliveryWarehouse: '',
          requireGoodsWarehouse: ''
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable', ],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            // { title: '仓库名称', key: 'depotId', width: '7%', type: FormTypes.select, placeholder: '请选择${title}', options: [],
            //   allowSearch:true, validateRules: [{ required: true, message: '${title}不能为空' }]
            // },
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '6%', type: FormTypes.hidden },
            // { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '20%', type: FormTypes.popupJsh, kind: 'material', multi: true,
            //   // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            // },
            { title: this.$t('otherJS.goodsId'), key: 'meId', width: '6%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.name'), key: 'name', width: '16%', type:  FormTypes.popupJsh, kind: 'material', multi: true},
            { title: this.$t('reportQuery.specification'), key: 'standard', width: '15%', type: FormTypes.normal },
            { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.input,readonly:true  },
            { title: this.$t('reportQuery.model'), key: 'model', width: '5%', type: FormTypes.normal },
            { title: this.$t('reportQuery.color'), key: 'color', width: '5%', type: FormTypes.normal },
            { title: this.$t('reportQuery.extendedInformation'), key: 'materialOther', width: '5%', type: FormTypes.normal },
            { title: this.$t('reportQuery.inventory'), key: 'stock', width: '10%', type: FormTypes.normal },
            // { title: '调入仓库', key: 'anotherDepotId', width: '7%', type: FormTypes.select, placeholder: '请选择${title}', options: [], allowSearch:true},
            { title: this.$t('reportQuery.unit'), key: 'unit', width: '8%', type: FormTypes.normal },
            { title: this.$t('inPrint.serialNumber'), key: 'snList', width: '12%', type: FormTypes.popupJsh, kind: 'sn', multi: true },
            // { title: this.$t('commodityManagement.batchNumber'), key: 'batchNumber', width: '7%', type: FormTypes.popupJsh, kind: 'batch', multi: false },
            { title: this.$t('inPrint.termValidity'), key: 'expirationDate',width: '6%', type: FormTypes.normal },
            { title: this.$t('commodityManagement.multiAttribute'), key: 'sku', width: '4%', type: FormTypes.normal },
            { title: this.$t('reportQuery.quantity'), key: 'operNumber', width: '8%', type: FormTypes.inputNumber, statistics: true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            // { title: this.$t('reportQuery.unitPrice'), key: 'unitPrice', width: '5%', type: FormTypes.inputNumber},
            // { title: this.$t('reportQuery.amount'), key: 'allPrice', width: '5%', type: FormTypes.inputNumber, statistics: true },
            { title: this.$t('financialManagement.remarks'), key: 'remark', width: '10%', type: FormTypes.input },
            // 必传又不显示字段
            { title: '', key: 'custom2', width: '0', type: FormTypes.hidden },
            { title: '', key: 'custom13', width: '0', type: FormTypes.hidden },
            { title: '', key: 'ratio', width: '0', type: FormTypes.hidden },
          ]
        },
        UserHandler: [],
        confirmLoading: false,
        validatorRules:{
          anotherDepotId:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDistriWarehouse')+'!' }
            ]
          },
          depotId:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectPurWarehouse')+'!' }
            ]
          },
          operTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
          type:{
            rules: [
              { required: true, message: this.$t('basicInformation.pleaseType')+'!' }
            ]
          },
          number:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          }
        },
        url: {
          list: "/person/list",
          add: '/depotHead/addDepotHeadAndDetail',
          edit: '/depotHead/updateDepotHeadAndDetail',
          detailList: '/depotItem/getDetailList'
        }
      }
    },
    created () {
      this.getDepotData()
      this.getAnotherDepotData()
    },
    methods: {
      // 获取经手人
      getHandler() {
        let param = {
          // 'search': {"name":"","type":""},
          // 'column': 'createTime',
          // 'order': 'desc',
          // 'field': 'id,,,name,type,action',
          'currentPage': '1',
          'pageSize': '10'
        }
        getAction("/person/list", param).then(res=>{
          if(res.code == '200') {
            this.UserHandler = res.data.rows
          }
        })
      },
      changeType(val) {
        this.form.setFieldsValue({
          department: val
        })
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.arrList = []
        this.getHandler()
        this.billStatus = '0'
        this.changeColumnHide()
        this.changeFormTypes(this.materialTable.columns, 'snList', 0)
        // this.changeFormTypes(this.materialTable.columns, 'batchNumber', 0)
        this.changeFormTypes(this.materialTable.columns, 'expirationDate', 0)
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
        } else {
          this.model.operTime = this.model.operTimeStr
          
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'deliveryMethod', 'arrivalTime', 'anotherDepotId', 'depotId', 'salesMan', 'department', 'operTime', 'number', 'remark',
              'discount','discountMoney','discountLastMoney','otherMoney','accountId','changeAmount'))
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable);
          let arr = []
          this.materialTable.dataSource.forEach(item => {
            arr.push(item.materialId)
          });
          this.materialIds = arr.toString()
          this.changeMaterialIds()
        }
        //复制新增单据-初始化单号和日期
        if(this.action === 'copyAdd') {
          this.model.id = ''
          this.model.tenantId = ''
          this.copyAddInit(this.prefixNo)
        }
        this.initDepot()
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '其它'
        billMain.subType = '要货申请'
        billMain.defaultNumber = billMain.number
        for(let item of detailArr){
          totalPrice += item.allPrice - 0
          item.custom2 = item.color
          item.custom13 = item.ratio || item.custom13
        }
        billMain.totalPrice = totalPrice
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // } else {
        //   billMain.fileName = ''
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      depotSelectChange(e){
        console.log('666 :>> ', 666);
        this.depotId = e
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>